package com.xiyuan.handler;

import com.xiyuan.constant.MessageConstant;
import com.xiyuan.constant.UserConstant;
import com.xiyuan.pojo.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        e.printStackTrace();
        return Result.error(StringUtils.hasLength(e.getMessage()) ? e.getMessage() : "操作失败");
    }

    /**
     * 数据库异常处理
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(DataIntegrityViolationException.class)
    public Result handleDataIntegrityViolationException(DataIntegrityViolationException ex) {
        String message = ex.getMessage();
        log.info(message);
        if (message.contains("Duplicate entry")) {
            String[] split = message.split(" ", 3);  // 使用有限分割次数，避免数组越界
            if (split.length >= 3) {
                String username = split[1].replace("\"", "");  // 更安全地提取用户名
                String msg = username + UserConstant.ALREADY_EXISTS;
                return Result.error(msg);
            }
        }
        if (message.contains("cannot be null")) {
            return Result.error(MessageConstant.PARAMETER_ERROR);
        }
        if (message.contains("foreign")) {  // 使用正确的变量名
            return Result.error(MessageConstant.DELETE_FAIL);
        }
        return Result.error(MessageConstant.UNKNOWN_ERROR);
    }

}
